//
//  BenefitBoardViewController.swift
//  SitPosition
//
//  Created by apple on 2019/1/1.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography


/**
 * 收益数据模型
 */
struct Benefit : Codable {
    let id: String
    let userId: String?     // 用户id
    let info: String?       // 收益信息
    let createTime: Int?    // 创建时间，毫秒
}


/**
 * 收益列表页面
 */
let kVMargin: CGFloat = 5

class BenefitBoardViewController : GKNavigationBarViewController {
    
    // MARK: - Properties
    
    // 数据集
    var _dataList: [Benefit] = []
    
    // UI
    lazy var tipBanner: UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.layer.cornerRadius = 5
        button.backgroundColor = Theme.Color.primaryBlueTextColor
        button.titleLabel?.font = Theme.Font.regularFont(ofSize: 14)
        button.setTitle(Strings.incomingTip, for: UIControl.State.normal)
        button.setTitleColor(UIColor.white, for: UIControl.State.normal)
        return button
    }()
    
    lazy var tableView: PageableTableView = {
        let tv = PageableTableView(frame: CGRect.zero, style: UITableView.Style.plain)
        tv.backgroundView = {
            let bkView = UIView()
            bkView.backgroundColor = Theme.Color.primaryBackgroundColor
            return bkView
        }()
        tv.estimatedRowHeight = UITableView.automaticDimension
        tv.separatorStyle = .none
        tv.dataSource = self
        tv.delegate = self
        tv.register(BenefitCell.self, forCellReuseIdentifier: BenefitCell.reusedIdentifier)
        tv.loadHandler = { [weak self] page, success, failure in
            self?._fetchData(page, succes: success, failure: { (error) in
                self?.view.makeToast(error?.networkErrorMessage ?? Strings.networkError)
                failure(error)
            })
        }
        return tv
    }()
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = Strings.incomingList
        
        // 导航栏
        gk_navTitle = title
        gk_navLineHidden = true
        gk_navBackgroundColor = UIColor.white
        gk_navLeftBarButtonItem = UIBarButtonItem(imageName: "ic_nav_back_black", target: self, action: #selector(_backButtonTapped))
        
        // 配置View
        view.backgroundColor = Theme.Color.primaryBackgroundColor
        view.addSubview(tipBanner)
        view.addSubview(tableView)
        _setupContraints()
        
        // 拉取数据
        tableView.mj_header.beginRefreshing()
    }
}

// MARK: - Private Methods

extension BenefitBoardViewController {
    
    // 设置视图约束
    func _setupContraints() {
        let kTipBannerH: CGFloat = 30
        
        // tipBanner
        constrain(tipBanner, gk_navigationBar, view) { v, sibling, parent in
            v.top == sibling.bottom + 10
            v.left == parent.left + 15
            v.right == parent.right - 15
            v.height == kTipBannerH
        }
        
        // tableView
        constrain(tableView, tipBanner, view) { v, sibling, parent in
            v.top == sibling.bottom + kVMargin
            v.left == parent.left
            v.right == parent.right
            v.bottom == parent.bottom
        }
    }
    
    // 拉取数据
    // @isMore：YES - 下拉刷新数据；NO - 上拉加载更多
    func _fetchData(_ page: Int,
                    succes: @escaping PageableLoadResultBlock,
                    failure: @escaping PageableFetchFailureBlock) {
        NetworkClient.instance.viewUserIncoming(page: page, success: { [weak self] (data) in
            guard let sself = self else { return }
            guard let data_ = data else {
                failure(SPError.unexpectedServerResponse)
                return
            }
            do {
                let decoder = JSONDecoder()
                let pagable: PagableData<Benefit> = try decoder.decode(PagableData<Benefit>.self, from: data_)
                if let content = pagable.content {
                    if page == 0 {
                        sself._dataList = content
                    } else {
                        sself._dataList.append(contentsOf: content)
                    }
                }
                let isLastPage = pagable.last ?? true
                succes((pagable.content?.count ?? 0), isLastPage)
            } catch {
                failure(error)
            }
        }, failure: { (error) in
            failure(error)
        })
    }
    
    // 返回按钮点击事件
    @objc func _backButtonTapped() {
        if presentingViewController != nil {
            dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
    
}

// MARK: - UITableViewDataSource / UITableViewDelegate

extension BenefitBoardViewController : UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return _dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: BenefitCell = tableView.dequeueReusableCell(withIdentifier: BenefitCell.reusedIdentifier, for: indexPath) as! BenefitCell
        cell.title = _dataList[indexPath.row].info
        return cell
    }
}


